<template>
  <!-- 设备管理--传感器管理 -->
  <div class="app-container table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label prop="grade">
        <selector
          type="sensorType"
          size="small"
          style="width: 160px"
          clearable
          placeholder="请选择传感器类型"
          v-model="queryParams.sensorTypeId"
        ></selector>
      </el-form-item>
      <el-form-item label prop="grade">
        <selector
          ref="statusSelector"
          type="sensorState"
          size="small"
          style="width: 160px"
          clearable
          placeholder="请选择传感器状态"
          v-model="queryParams.statusOption"
        ></selector>
      </el-form-item>
      <el-form-item label prop="keywords">
        <el-input v-model="queryParams.deviceName" placeholder="模糊搜索传感器名称" clearable size="small" />
      </el-form-item>
      <el-form-item label prop="keywords">
        <el-input v-model="queryParams.deviceNumber" placeholder="模糊搜索传感器编号" clearable size="small" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" @click="handleQuery" type="primary">搜索</el-button>
        <el-button size="mini" :disabled="!ids.length" @click="handleMaintain" type="primary">批量维护</el-button>
        <el-button size="mini" :disabled="!ids.length" @click="handleStart" type="primary">批量启用</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="mini" :data="operationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column prop="seq" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="name" label="传感器名称" width="150px" align="center"></el-table-column>
      <el-table-column prop="sensorTypeId" label="传感器类型" align="center"></el-table-column>
      <el-table-column prop="number" label="传感器编号" align="center"></el-table-column>
      <el-table-column prop="lon" label="经度" width="100px" align="center"></el-table-column>
      <el-table-column prop="lat" label="纬度" width="100px" align="center"></el-table-column>
      <el-table-column prop="jointTime" min-width="160" label="设备接入时间" align="center"></el-table-column>
      <el-table-column prop="expireTime" min-width="160" label="设备运行总时长" align="center"></el-table-column>
      <el-table-column prop="status" label="传感器状态" align="center" :formatter="statusFormater"></el-table-column>
      <el-table-column prop="repairTimes" label="维护次数" align="center"></el-table-column>
      <el-table-column prop="operation" label="操作" width="240px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn"  @click="handleView(scope.row)" >查看</el-button>
          <el-button v-if="scope.row.status!=2" size="mini" class="btn" @click="handleRepair(scope.row)" >维护</el-button>
          <el-button  v-if="scope.row.status==2" size="mini" class="btn" @click="handleStartSingle(scope.row)">恢复使用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>

<script>

  import { listSensor,editDeviceState2 } from '@/api/page/device.js';
  import selector from "@/views/components/selector";

  export default {
    name: "equipment",
    components: {
      selector
    },
    data() {
      return {
        // 展示组件
        showComponentInfo: {
          title: "",
          open: false,
          form: {
            name: "",
            sensorTypeId: "",
            number: "",
            imei: "",
            pointName: "",
            site: {
              address: "",
              lon: "",
              lat: ""
            },
            thresholdValue: {
              first: "",
              second: "",
              third: ""
            }
          }
        },
        // 角色表格数据
        operationList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          sensorTypeId: undefined,
          statusOption: undefined,
          deviceName: undefined,
          deviceNumber: undefined
        },
        // 条件查询日期参数
        dateRange: [],
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        typeOptions: [],
        stateOptions: []
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询传感器列表 */
      getList() {
        let self = this;
        self.loading = true;
        listSensor(self.addDateRange(self.queryParams, self.dateRange)).then(response => {
          var data = response.rows;
          self.total = response.total;
          self.operationList = [];
          for (var i = 0; i < data.length; i++) {
            var sensor = data[i];
            var device = sensor.device;
            var sensorType = sensor.sensorType;
            var point = device.point;
            var moniterItem = sensor.monitorItems[0];
            self.operationList.push({
              deviceId:device.deviceId,
              sensorId:sensor.sensorId,
              seq: sensor.sensorId,
              name: device.deviceName,
              sensorTypeId: sensorType.typeName,
              number: device.number,
              imei: device.imei,
              pointName: point.pointName,
              jointTime: self.handleTimeFarmat(device.joinTime),
              status: device.state,
              expireTime: self.handleSensorHandleTime(device.joinTime, device.onlineTime),
              repairTimes: sensor.repairTimes,
              lon: point.lon,
              lat: point.lat,
              thresholdValue: {
                first: moniterItem.threshold1,
                second: moniterItem.threshold2,
                third: moniterItem.threshold3
              }
            });
          }
          self.loading = false;
        }).catch((error)=>{
          self.loading = false;
					console.log(error);
				});
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.deviceId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 查看按钮操作 */
      handleView(row) {
        let self = this;
        self.$router.push({path: '/device/device-repair?id=' + row.sensorId+"&num="+row.number});
      },
      /** 维护按钮操作 */
      handleRepair(row) {
        var self = this;
        this.$confirm( "处于维护状态的设备将不在发送监测信息，是否确认维护？", "维护提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error"
          })
          .then(function () {
            var obj ={
              state:2,
              devices:row.deviceId
            };
            editDeviceState2(obj).then(response => {
              if (response.code === 200) {
                self.msgSuccess("维护成功");
                self.getList();
              } else {
                self.msgError(response.msg);
              }
            });
          })
          .then(response => {
          })
          .catch((error)=>{
					  console.log(error);
				  });
        //todo
      },
      /** 提交按钮 */
      // 批量维护
      handleMaintain() {
        var self = this;
        this.$confirm('确认要批量维护吗？处于维护状态的设备将不在发送监测信息，是否确认维护？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error"
        }).then(function () {
          var obj ={
            state:2,
            devices:self.ids.join(",")
          };
          editDeviceState2(obj).then(response => {
            if (response.code === 200) {
              self.msgSuccess("批量维护成功");
              self.getList();
            } else {
              self.msgError(response.msg);
            }
          });
        }).then(() => {
          // this.msgSuccess(text + "成功");
        }).catch(function () {

        });
      },
      //恢复使用
      handleStartSingle(row){
        var self = this;
        this.$confirm(
          "确认要恢复此设备吗？",
          "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error"
          }
        )
          .then(function () {
            var obj ={
              state:0,
              devices:row.deviceId
            };
            editDeviceState2(obj).then(response => {
              if (response.code === 200) {
                self.msgSuccess("启用成功");
                self.getList();
              } else {
                self.msgError(response.msg);
              }
            });
          })
          .then(response => {
          })
          .catch(function () {
          });
      },
      // 批量启用
      handleStart() {
        var self = this;
        this.$confirm('确认要批量启用吗？', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          var obj ={
            state:0,
            devices:self.ids.join(",")
          };
          editDeviceState2(obj).then(response => {
            if (response.code === 200) {
              self.msgSuccess("批量启用成功");
              self.getList();
            } else {
              self.msgError(response.msg);
            }
          }).catch((error)=>{
            console.log(error);
          });
        }).then(() => {
          // this.msgSuccess(text + "成功");
        }).catch(function () {

        });
      },
      //时间格式处理
      handleTimeFarmat(val) {
        return val!=null?val.substring(0, 10) + " " + val.substring(11, 19):'';
      },
      //运行时间处理
      handleSensorHandleTime(join, online) {
        if(online==null) {
          return "设备未正常运行";
        }
        var joinStramp = new Date(online).getTime();
        var onlineStramp = new Date().getTime();
        return this.secondsFormat(onlineStramp - joinStramp);
      },
      //秒转成时间格式
      secondsFormat(s) {
        if(s<=0){
          return "未运行";
        }

        s = s/1000;
        var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整
        var hour = Math.floor((s - day * 24 * 3600) / 3600);
        var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
        var second =Math.floor( s - day * 24 * 3600 - hour * 3600 - minute * 60);
        var str="";
        if(day!=0){
          str +=day + "天";
        }
        if(hour!=0){
          str+=hour + "时";
        }
        if(minute!=0){
          str+=minute + "分";
        }
        return str + second + "秒";
      },
      statusFormater(row, column) {
				let i = this.$refs.statusSelector.getItem(row.status);
				return (i && i.label) || "";
			}
    }
  };
</script>
<style lang="scss">
  .el-table--group, .el-table--border, .el-table th.is-leaf, .el-table--border th, .el-table td, .el-table--border th, .el-table--border td {
    border: 0px;
  }

  // 去掉table内部线条
  .el-table--border tr,
  td {
    border-bottom: 1px solid rgb(223, 230, 236) !important;
  }

  .el-table__header-wrapper th:nth-last-of-type(9) {
    border: 0px !important;
  }

  .select1 {
    width: 180px;
    height: 32px;
  }

  .el-table::before {
    // 去掉table最下面的边框线
    height: 0;
  }

  .el-table {
    // 去掉table最右边的边框线
    position: static;
  }

  .green {
    color: rgb(20, 210, 20);
  }

  .el-table_1_column_12_column_13>.cell {
    color: #409eff;
  }

  .el-table_1_column_12_column_14>.cell {
    color: #e6a23c;
  }

  .el-table_1_column_12_column_15>.cell {
    color: #f56c6c;
  }
</style>
